package com.yc;

import org.springframework.beans.PropertyAccessor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;

@Configuration
@PropertySource("classpath:smtp.properties")
public class SmtpConfig {

    @Value("${smtp.username}")
    private String username;
    @Value("${smtp.password}")
    private String password;
    @Value("${smtp.host}")
    private String host;
    @Value("${smtp.auth}")
    private String auth;
    @Value("${smtp.port}")
    private String port;
    @Value("${smtp.from}")
    private String from;

    @Bean
    public JavaMailSender mailSender() {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setUsername(username);
        javaMailSender.setPassword(password);
        javaMailSender.setHost(host);
        javaMailSender.setPort(Integer.parseInt(port));
        Properties p = javaMailSender.getJavaMailProperties();
        p.put("mail.smtp.auth", auth);
        p.put("mail.transport.protocol", "smtp");
        p.put("mail.smtp.ssl.protocols", "TLSv1.2");
        if (port.equals("587")) {
            p.put("mail.smtp.starttls.enable", "true");
        }
        if (port.equals("465")) {
            p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            p.put("mail.smtp.socketFactory.port", "465");
            p.put("spring.mail.properties.mail.smtp.ssl.enable", "true");
        }
        return javaMailSender;
    }
}
